﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Media.Media3D;
using System.Windows;
using System.Windows.Media;
using System.Windows.Controls;

namespace EveruWPF.Windows.V3D
{
    /// <summary>
    /// Returnes the GeometryModel3D, which were hitted at the Point mousePos
    /// </summary>
    internal class ViewportHitTestHandler
    {
        private List<RayMeshGeometry3DHitTestResult> Hits = new List<RayMeshGeometry3DHitTestResult>();

        /// <summary>
        /// Start calculation
        /// </summary>
        /// <param name="Vis">The Viewport3D</param>
        /// <param name="Callback"></param>
        /// <param name="mousePos">The Mouseposition, where the Viewport3D where hitted</param>
        public void StartHitTest(Viewport3D Vis, HitTestHandlerResult Callback, Point mousePos)
        {
            PointHitTestParameters hitParams = new PointHitTestParameters(mousePos);
            VisualTreeHelper.HitTest(Vis, null, ResultCallback, hitParams);

            var HitQuery = from o in Hits orderby o.DistanceToRayOrigin select o;
            if (HitQuery.Count() > 0)
            {
                Callback(((RayMeshGeometry3DHitTestResult)HitQuery.First()).ModelHit as GeometryModel3D, Vis);
            }

        }

        private HitTestResultBehavior ResultCallback(HitTestResult result)
        {
            // Did we hit 3D?
            RayHitTestResult rayResult = result as RayHitTestResult;
            if (rayResult != null)
            {
                // Did we hit a MeshGeometry3D?
                RayMeshGeometry3DHitTestResult rayMeshResult =
                    rayResult as RayMeshGeometry3DHitTestResult;

                if (rayMeshResult != null)
                {
                    Hits.Add(rayMeshResult);
                }
            }

            return HitTestResultBehavior.Continue;
        }

    }


    public delegate void HitTestHandlerResult(GeometryModel3D Result, Viewport3D Port);
}
